package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcity.game.guild.gmember.GuildMemberData;
import com.xcity.game.guild.gmember.GuildMemberDonate;

public class GuildMemberDataTypeHandler extends BaseTypeHandler<GuildMemberData> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, GuildMemberData parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null? parameter.toString() : "");
	}

	@Override
	public GuildMemberData getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public GuildMemberData getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public GuildMemberData getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}

	public static GuildMemberData parse(String json){
		if(StringUtils.isEmpty(json)){
			return new GuildMemberData(null, 0).checkVersion(0);
		}
		String[] strs = naga.x.util.StringUtils.split(json, ";");
		if(strs.length == 3){
			int lastDay = Integer.parseInt(strs[1]);
			JSONObject map = JSON.parseObject(strs[2]);
			Map<Integer, GuildMemberDonate> newMap = new ConcurrentHashMap<Integer, GuildMemberDonate>();
			for(String typeStr : map.keySet()){
				String val = map.getString(typeStr);
				GuildMemberDonate guildmember = (GuildMemberDonate)JSON.parseObject(val, GuildMemberDonate.class);
				newMap.put(Integer.parseInt(typeStr), guildmember);
				return new GuildMemberData(newMap, lastDay).checkVersion(Integer.parseInt(typeStr));
			}
		}
		return new GuildMemberData(null, 0).checkVersion(0);
	}
}
